import { showLoading, hideLoading, showError } from "./common";

// 请求基础配置
const baseConfig = {
  baseURL: "",
  timeout: 10000,
  header: {
    "content-type": "application/json",
  },
};

// 请求拦截器
const requestInterceptor = (config) => {
  //showLoading("加载中");
  return config;
};

// 响应拦截器
const responseInterceptor = (response) => {
  hideLoading();
  return response.data;
};

// 错误处理
const errorHandler = (error) => {
  hideLoading();
  return Promise.reject(error);
};

// 请求方法
export default function request(config) {
  const finalConfig = {
    ...baseConfig,
    ...config,
    header: {
      ...baseConfig.header,
      ...config.header,
    },
  };

  // 应用请求拦截器
  requestInterceptor(finalConfig);

  return new Promise((resolve, reject) => {
    uni.request({
      ...finalConfig,
      success: (res) => {
        resolve(responseInterceptor(res));
      },
      fail: (error) => {
        reject(errorHandler(error));
      },
    });
  });
}
